package JUC;

//synchronized 实现生产者消费者,对一个数进行增1或减1
public class Producter_Consumer_Synchronized {

    public static void main(String[] args) {
        Test test = new Test();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    test.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    test.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

    }
}

class Test{
    private int i = 0;
    public synchronized void increase() throws InterruptedException {
        while (i==1){
            //防止虚假唤醒
            //此时不用加
            this.wait();
        }
        i++;
        System.out.println(Thread.currentThread().getName() + "增加了1，现在i为"+i);
        this.notifyAll();  //唤醒消费者
    }

    public synchronized  void decrease() throws InterruptedException {
        //防止虚假唤醒
        while(i==0){
            this.wait();
        }
        i--;
        System.out.println(Thread.currentThread().getName() + "减少了1，现在i为"+i);
        this.notifyAll();  //唤醒生产
    }
}


class Test1 implements Runnable{
    private  int i = 0;


    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        synchronized (this){

        }
    }
}